package com.farmer.announcement.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.farmer.announcement.mapper.AnnouncementMapper;
import com.farmer.announcement.service.AnnouncementService;
import com.farmer.common.entity.Announcement;
import com.farmer.common.result.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 公告服务实现类
 */
@Slf4j
@Service
public class AnnouncementServiceImpl implements AnnouncementService {

    @Autowired
    private AnnouncementMapper announcementMapper;

    @Override
    public Result<?> getAnnouncementList(Integer pageNum, Integer pageSize, String type, String keyword, Integer isPublished) {
        try {
            Page<Announcement> page = new Page<>(pageNum, pageSize);
            QueryWrapper<Announcement> queryWrapper = new QueryWrapper<>();

            // 类型过滤
            if (StringUtils.hasText(type)) {
                queryWrapper.eq("type", type);
            }

            // 发布状态过滤
            if (isPublished != null) {
                queryWrapper.eq("is_published", isPublished);
            }

            // 关键词搜索（标题、内容、作者）
            if (StringUtils.hasText(keyword)) {
                queryWrapper.and(wrapper -> wrapper
                    .like("title", keyword)
                    .or()
                    .like("content", keyword)
                    .or()
                    .like("author", keyword)
                );
            }

            // 按发布时间倒序，再按创建时间倒序
            queryWrapper.orderByDesc("publish_time", "create_time");

            Page<Announcement> announcementPage = announcementMapper.selectPage(page, queryWrapper);

            Map<String, Object> result = new HashMap<>();
            result.put("records", announcementPage.getRecords());
            result.put("total", announcementPage.getTotal());
            result.put("pageNum", pageNum);
            result.put("pageSize", pageSize);

            return Result.success("获取公告列表成功", result);
        } catch (Exception e) {
            log.error("获取公告列表失败：{}", e.getMessage(), e);
            return Result.error("获取公告列表失败");
        }
    }

    @Override
    public Result<?> getAnnouncementById(Long announcementId) {
        try {
            if (announcementId == null) {
                return Result.error("公告ID不能为空");
            }

            Announcement announcement = announcementMapper.selectById(announcementId);
            if (announcement == null) {
                return Result.error("公告不存在");
            }

            return Result.success("获取公告详情成功", announcement);
        } catch (Exception e) {
            log.error("获取公告详情失败：{}", e.getMessage(), e);
            return Result.error("获取公告详情失败");
        }
    }

    @Override
    public Result<?> addAnnouncement(Announcement announcement) {
        try {
            if (announcement == null) {
                return Result.error("公告信息不能为空");
            }

            // 基本验证
            if (!StringUtils.hasText(announcement.getTitle())) {
                return Result.error("公告标题不能为空");
            }
            if (!StringUtils.hasText(announcement.getContent())) {
                return Result.error("公告内容不能为空");
            }

            // 设置默认值
            if (!StringUtils.hasText(announcement.getType())) {
                announcement.setType("NOTICE");
            }
            if (announcement.getPriority() == null) {
                announcement.setPriority(1);
            }
            if (announcement.getViewCount() == null) {
                announcement.setViewCount(0);
            }
            if (announcement.getIsPublished() == null) {
                announcement.setIsPublished(0); // 默认为草稿状态
            }

            int result = announcementMapper.insert(announcement);
            if (result > 0) {
                log.info("添加公告成功：{}", announcement.getTitle());
                return Result.success("添加公告成功");
            } else {
                return Result.error("添加公告失败");
            }
        } catch (Exception e) {
            log.error("添加公告失败：{}", e.getMessage(), e);
            return Result.error("添加公告失败");
        }
    }

    @Override
    public Result<?> updateAnnouncement(Announcement announcement) {
        try {
            if (announcement == null || announcement.getId() == null) {
                return Result.error("公告信息不能为空");
            }

            // 检查公告是否存在
            Announcement existAnnouncement = announcementMapper.selectById(announcement.getId());
            if (existAnnouncement == null) {
                return Result.error("公告不存在");
            }

            int result = announcementMapper.updateById(announcement);
            if (result > 0) {
                log.info("更新公告成功：{}", announcement.getTitle());
                return Result.success("更新公告成功");
            } else {
                return Result.error("更新公告失败");
            }
        } catch (Exception e) {
            log.error("更新公告失败：{}", e.getMessage(), e);
            return Result.error("更新公告失败");
        }
    }

    @Override
    public Result<?> deleteAnnouncement(Long announcementId) {
        try {
            if (announcementId == null) {
                return Result.error("公告ID不能为空");
            }

            // 检查公告是否存在
            Announcement announcement = announcementMapper.selectById(announcementId);
            if (announcement == null) {
                return Result.error("公告不存在");
            }

            int result = announcementMapper.deleteById(announcementId);
            if (result > 0) {
                log.info("删除公告成功：{}", announcement.getTitle());
                return Result.success("删除公告成功");
            } else {
                return Result.error("删除公告失败");
            }
        } catch (Exception e) {
            log.error("删除公告失败：{}", e.getMessage(), e);
            return Result.error("删除公告失败");
        }
    }

    @Override
    public Result<?> publishAnnouncement(Long announcementId, Integer isPublished) {
        try {
            if (announcementId == null || isPublished == null) {
                return Result.error("参数不能为空");
            }

            if (isPublished != 0 && isPublished != 1) {
                return Result.error("发布状态值无效");
            }

            Announcement announcement = announcementMapper.selectById(announcementId);
            if (announcement == null) {
                return Result.error("公告不存在");
            }

            announcement.setIsPublished(isPublished);
            if (isPublished == 1) {
                announcement.setPublishTime(LocalDateTime.now());
            }

            int result = announcementMapper.updateById(announcement);
            if (result > 0) {
                String operation = isPublished == 1 ? "发布" : "取消发布";
                log.info("{}公告成功：{}", operation, announcement.getTitle());
                return Result.success(operation + "公告成功");
            } else {
                return Result.error("操作失败");
            }
        } catch (Exception e) {
            log.error("发布公告失败：{}", e.getMessage(), e);
            return Result.error("发布公告失败");
        }
    }

    @Override
    public Result<?> getLatestAnnouncements(Integer limit) {
        try {
            QueryWrapper<Announcement> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("is_published", 1);
            queryWrapper.orderByDesc("publish_time");
            queryWrapper.last("LIMIT " + limit);

            List<Announcement> announcements = announcementMapper.selectList(queryWrapper);

            return Result.success("获取最新公告成功", announcements);
        } catch (Exception e) {
            log.error("获取最新公告失败：{}", e.getMessage(), e);
            return Result.error("获取最新公告失败");
        }
    }

    @Override
    public Result<?> incrementViewCount(Long announcementId) {
        try {
            if (announcementId == null) {
                return Result.error("公告ID不能为空");
            }

            Announcement announcement = announcementMapper.selectById(announcementId);
            if (announcement == null) {
                return Result.error("公告不存在");
            }

            // 增加浏览次数
            announcement.setViewCount(announcement.getViewCount() + 1);
            int result = announcementMapper.updateById(announcement);

            if (result > 0) {
                return Result.success("浏览次数更新成功");
            } else {
                return Result.error("浏览次数更新失败");
            }
        } catch (Exception e) {
            log.error("更新浏览次数失败：{}", e.getMessage(), e);
            return Result.error("更新浏览次数失败");
        }
    }
} 